import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/log_utils.dart';

import 'package:yt_devops/pages/site/site_observer_list/site_observer_list_model.dart';
import 'package:yt_devops/pages/site/site_observer_list/views/ess_monitor.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/func_utils.dart';

class SiteObserverListController extends GetxController
    with GetTickerProviderStateMixin {
  SiteObserverListModel state = SiteObserverListModel();
  DeviceServices services = Get.put(DeviceServices());
  SiteServices siteServices = Get.put(SiteServices());
  bool isLoad = false;
  int selectedTitleIndex = 0;
  late int siteId;
  var allDataMap = {}; //返回的所有监控数据
  var mainsDataMap = {}; //市电
  var photovoltaicDataMap = {}; //光伏
  var energyDataMap = {}; //储能
  var chargeDataMap = {}; //充电桩
  var otherDataMap = {}; //其他负载监控
  List<String> tabs = [
    ResKey.siteSettingObserverElectricityObserver.tr,
    ResKey.siteSettingObserverPhotovoltaicObserver.tr,
    ResKey.siteSettingObserverStoreEnergyObserver.tr,
    ResKey.siteSettingObserverChargeObserver.tr,
    ResKey.siteSettingObserverOtherLoadObserver.tr
  ];
  late TabController tabController =
      TabController(length: tabs.length, vsync: this);
  // List<dynamic> postList = [];//保存需要上传的所有数据
  final GlobalKey<EssMonitorWidgetState> childKey = GlobalKey();

  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['siteId'];
      getAllDataList();
    }
    super.onInit();
    tabController.addListener(() {
      Log.d('abController.index==' + tabController.index.toString());
      setSelectedTitleIndex(tabController.index, tabController.index);
      FocusScope.of(Get.context!).requestFocus(FocusNode());
      update();
      // updateElecType(tabController.index);
    });
    // 创建键盘可见性监测器
    final keyboardVisibilityController = KeyboardVisibilityController();
    // 订阅键盘可见性变化
    keyboardVisibilityController.onChange.listen((bool visible) {
      // 在这里处理键盘可见性变化的逻辑
      if (visible) {
        // 键盘弹出时的处理逻辑
        print('Keyboard is visible');
      } else {
        // 键盘隐藏时的处理逻辑
        mainsDataMap =   _handleOriginData(mainsDataMap);
        update();
      }
    });

  }

  @override
  void onReady() {
    Log.d('SiteObserverListControlleronReady==');
  }

  @override
  void onClose() {

  }

  Future<void> setSelectedTitleIndex(int index, int subSystemId) async {
    selectedTitleIndex = index;
    // 刷新数据
    update();
  }

  ///处理需要上传的数据
  savePostData(List<dynamic> dataList, int subType) {
    //2代表充电量、发电量、用电量 3代表放电量、上网电量 4代表功率
    int tabType = 5;
    if (tabController.index == 0) {
      //1 光伏 =2储能 =3充电桩 =4负载 =5市电
      tabType = 5;
    } else if (tabController.index == 1) {
      tabType = 1;
    } else if (tabController.index == 2) {
      tabType = 2;
    } else if (tabController.index == 3) {
      tabType = 3;
    } else if (tabController.index == 4) {
      tabType = 4;
    }

    ///设置返回数据的类型和子类型
    for (var element in dataList) {
      element['type'] = tabType;
      element['subType'] = subType;
      element['siteId'] = siteId;
    }
    if (allDataMap[tabType.toString()]['valueMap'] == null) {
      //如果valueMap为空,对空对象赋值会报错
      allDataMap[tabType.toString()]['valueMap'] = {};
    }
    allDataMap[tabType.toString()]['valueMap'][subType.toString()] = dataList;
    update();
  }

  ///获取监测点的所有数据
  getAllDataList() async {
    showLoading(toast: ResKey.loading.tr);
    var result = await services.getSiteObserverConfig({'siteId': siteId},
        onError: (error) {
      dismissLoading();
      return false;
    });

    dismissLoading();
    if (result != null) {
      allDataMap = result;
      if (allDataMap['5'] != null) {
        mainsDataMap = _handleOriginData(allDataMap['5']);
        mainsDataMap['isCanSwitch'] = true;
      }
      if (allDataMap['1'] != null) {
        photovoltaicDataMap = allDataMap['1'];
        photovoltaicDataMap['isCanSwitch'] = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingMonitorSettingPvStatus]);//光伏状态
      }
      if (allDataMap['2'] != null) {
        energyDataMap = allDataMap['2'];
        energyDataMap['isCanSwitch'] = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingMonitorSettingEssStatus]);//储能状态
      }
      if (allDataMap['3'] != null) {
        chargeDataMap = allDataMap['3'];
        chargeDataMap['isCanSwitch'] = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingMonitorSettingChargeStatus]);//充电桩状态
      }
      if (allDataMap['4'] != null) {
        otherDataMap = allDataMap['4'];
        otherDataMap['isCanSwitch'] = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingMonitorSettingOtherStatus]);//负载状态
      }
      update();
    }
  }

  ///处理原始数据,增加一个是否正在编辑的属性
  /// 处理原始数据的函数。
  /// 对给定的map进行处理，将特定键对应的list中的每个元素的'isEdit'键设置为false。
  ///
  /// @param map 原始数据的map，期望包含一个'valueMap'键，其下可能包含'2'，'3'，'4'等键，
  ///            对应的值为list，这些list的每个元素都是一个map。
  /// @return 返回处理后的map，确保'valueMap'下的相应列表中的元素的'isEdit'被设置为false。
  _handleOriginData(Map map){
    var tempMap = map;
    // 检查输入map及其'valueMap'键是否非空
    if(tempMap != null && tempMap['valueMap'] != null){
      // 针对'valueMap'下的'2'键对应的list进行处理
      if(tempMap['valueMap']['2'] != null){
        List list = tempMap['valueMap']['2'];
        // 仅在list非空时遍历设置'isEdit'为false
        if(list != null && list.isNotEmpty){
          for (var element in list) {
            element['isEdit'] = false;
          }
        }
      }
      // 同上，对'valueMap'下的'3'键对应的list进行处理
      if(tempMap['valueMap']['3'] != null){
        List list = tempMap['valueMap']['3'];
        if(list != null && list.isNotEmpty){
          for (var element in list) {
            element['isEdit'] = false;
          }
        }
      }
      // 同上，对'valueMap'下的'4'键对应的list进行处理
      if(tempMap['valueMap']['4'] != null){
        List list = tempMap['valueMap']['4'];
        if(list != null && list.isNotEmpty){
          for (var element in list) {
            element['isEdit'] = false;
          }
        }
      }
    }
    return tempMap;
  }

  ///点击编辑按钮跳转
  tapEditHandler(List<dynamic>? dataList, int type) {
    Get.toNamed(RouterPath.siteObserverDetail,
        arguments: {'siteId': siteId, 'dataList': dataList, 'type': type});
  }

  ///用户点击保存按钮 保存数据到服务器
  handleSave() async {
    List list = [];
    if (tabController.index == 0) {
      //市电
      list.addAll(_handleSaveEmptyData(mainsDataMap, 5, 2));
      list.addAll(_handleSaveEmptyData(mainsDataMap, 5, 3));
      list.addAll(_handleSaveEmptyData(mainsDataMap, 5, 4));
    } else if (tabController.index == 1) {
      //光伏
      list.addAll(_handleSaveEmptyData(photovoltaicDataMap, 1, 2));
      list.addAll(_handleSaveEmptyData(photovoltaicDataMap, 1, 3));
      list.addAll(_handleSaveEmptyData(photovoltaicDataMap, 1, 4));
    } else if (tabController.index == 2) {
      //储能
      list.addAll(_handleSaveEmptyData(energyDataMap, 2, 2));
      list.addAll(_handleSaveEmptyData(energyDataMap, 2, 3));
      list.addAll(_handleSaveEmptyData(energyDataMap, 2, 4));
    } else if (tabController.index == 3) {
      //充电桩
      list.addAll(_handleSaveEmptyData(chargeDataMap, 3, 2));
      list.addAll(_handleSaveEmptyData(chargeDataMap, 3, 4));
    } else if (tabController.index == 4) {
      //其他负载
      list.addAll(_handleSaveEmptyData(otherDataMap, 4, 2));
      list.addAll(_handleSaveEmptyData(otherDataMap, 4, 4));
    }
    if (list.isEmpty) {
      list = [
        {
          "deviceId": '',
          "deviceName": "",
          "deviceSN": "",
          "showName": "",
          "selectName": "",
          "paramName": "",
          "paramCode": "",
          "flag": '',
          "type": '',
          "subType": '',
          "siteId": ''
        },
      ];
    }

    if(tabController.index == 2 && childKey.currentState!=null && childKey.currentState!.selectedIndex == 0){
      EventBusUtil.getInstance().fire(SaveEssUnit());
    }else{
      showLoading(toast: ResKey.loading.tr);
      var result =
      await services.siteObserverObserverData(list, onError: (error) {
        handleException(error);
        dismissLoading();
        return false;
      });
      dismissLoading();
      if (result != null) {
        showSuccessToast(ResKey.mineUserManagerSaveSuccess.tr);
      }
    }

  }

  ///处理选择map中数据为空的处理
  _handleSaveEmptyData(Map<dynamic, dynamic>? map, int type, int subType) {
    List postList = [];
    if (map != null &&
        map['valueMap'] != null &&
        map['valueMap'][subType.toString()] != null) {
      List<dynamic> list = map['valueMap'][subType.toString()];
      if (list.isNotEmpty) {
        postList.addAll(map['valueMap'][subType.toString()]);
        return postList;
      }
    }
    return _handleEmptyList(type, subType);
  }

  ///处理空的数据传给后台
  _handleEmptyList(int type, int subType) {
    return [
      {"type": type, "subType": subType, "siteId": siteId},
    ];
  }

  ///监测点的开关状态切换
  obsStatusChange(bool isOpen, Map map) async {
    var param = {
      'siteId': siteId.toString(),
      'type': map['id'],
      'flag': (isOpen).toString()
    };
    Log.d('param==' + param.toString());
    showLoading(toast: ResKey.loading.tr);
    var result =
        await services.siteObserverObserverStatus(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      map['flag'] = isOpen;
    }
    update();
    Log.d('result==' + result.toString());
  }
}
